//
//  DataRepositoryManager.swift
//  
//
//  Created by 孙长坦 on 2022/3/28.
//

import Foundation

open class DataRepositoryManager {

    public static let shared = DataRepositoryManager()

    private var repositoryClasses: [String: DataRepositoryProtocol.Type] = [:]

    
    private var repositories: [String: DataRepositoryProtocol] = [:]
    
    public var repositoryDataCallback: ((_ id: String, _ encodeData: Any?) -> Void)?
    
    public var repositoryItemCallBack: ((_ id: String, _ encodeItem: Any?) -> Void)?
    
    private init() {
        
    }

    public func register(repositoryClass: DataRepositoryProtocol.Type) {
        repositoryClasses[repositoryClass.id] = repositoryClass
    }

    public func repository(id: String) -> DataRepositoryProtocol? {
        if let repository = repositories[id] {
            return repository
        }
        
        if let repository = repositoryClasses[id]?.init() {
            repositories[id] = repository
            
            repository.dataChangeCallBack = { [weak self] (_ encodeData: Any?) in
                self?.repositoryDataCallback?(id, encodeData)
            }
            
            repository.itemChangeCallBack = { [weak self] (_ encodeItem: Any?) in
                self?.repositoryItemCallBack?(id, encodeItem)
            }
            
            return repository
        }
        
        return nil
    }
}
